let db = require("../db/index");
const jwt = require('jsonwebtoken');
let { JWT_SECRET } = require('../jwt')
const moment = require('moment')


// 假设的用户数据库（在实际应用中，这将是数据库查询）
const users = [
    { username: 'admin', password: '123' } // 注意：不要在生产中存储明文密码！
];

// 图形验证码
const svgCaptcha = require('svg-captcha');

exports.captcha = (req, res) => {
    const captcha = svgCaptcha.create({
        size:4,
        ignoreChars:'0o1i9quv',
        noise:2,
        color:true,
        width:80,
        height:35,
    });
	res.type('svg');
	res.status(200).send(captcha);
};

exports.login = (req, res) => {
    console.log(req.body,22222222)
    const { username, password } = req.body
    const user = users.find(u => u.username === username && u.password === password );

    if (user) {
        // 生成 JWT
        const payload = { username: username };
        const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '12h' }); // Token 有效期为 1 小时

        // 获取 token 的过期时间（以秒为单位）
        const tokenExpiresInSeconds = parseInt(jwt.decode(token).exp) - Math.floor(Date.now() / 1000);
        
        
        var sql =
            `insert into loginlog(account,time,terminal,IP,address) value('${username}','${moment(new Date()).format("YYYY-MM-DD HH:mm:ss")}','Chrome浏览器','192.168.10.1','03:03:30:3A:3B:3C')`;
        db.query(sql, [], (err, data) => {
            if (err) {
                console.log("出错了", err);
                return res.send("错误" + err.message);
            }
            res.json({ token , expiresIn: tokenExpiresInSeconds }); // 将 Token 发送给客户端
        });
    } else {
        res.status(400).send('账号或密码错误,请重新输入')
    }
    
};
exports.project=(req, res) => {
    res.json({ message: 'This is a protected route', user: req.user });
}